package cn.stylefeng.guns.modular.system.service.Myservice;

import cn.stylefeng.guns.base.shiro.ShiroUser;
import cn.stylefeng.guns.modular.system.entity.*;
import cn.stylefeng.guns.modular.system.mapper.SalesOrderMapper;
import cn.stylefeng.guns.modular.system.model.params.PurchaseOrdersParam;
import cn.stylefeng.guns.modular.system.model.params.paramsDTO.CheckDTO;
import cn.stylefeng.guns.modular.system.model.params.paramsDTO.SaleOrderDTO;
import cn.stylefeng.guns.modular.system.service.*;
import cn.stylefeng.guns.sys.core.StatusCode.SalesOrderCode;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.util.utility.Katrina_CJ_Utils;
import cn.stylefeng.guns.sys.core.util.utility.Order;
import cn.stylefeng.guns.sys.core.util.utility.StatusCode;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author : xiaofei
 * @Date: 2019/7/4
 */
@Service
public class SalesOrService extends ServiceImpl<SalesOrderMapper, SalesOrder> {

    @Autowired
    private  PurchaseOrdersService purchaseOrdersService;
    @Autowired
    private  SalesOrderService salesOrderService;
    @Autowired
    private  DeptService deptService;
    @Autowired
    private  SalsOrderCheckService salsOrderCheckService;
    @Autowired
    private  DealerLevelService dealerLevelService;
    @Autowired
    private  AddressRoleService addressRoleService;
    @Autowired
    private  SalesOrService salesOrService;
    @Autowired
    private  CheckSalesService checkSalesService;
    @Autowired
    private  DispatchOrderService dispatchOrderService;
    @Autowired
    private  CommonService commonService;

    @Resource
    private RuntimeService runtimeService;
    @Resource
    private IdentityService identityService;
    @Resource
    private TaskService taskService;

    /**
     * 普通销售单
     * @param purchaseOrder
     * @param saleOrderDto
     */
    public void commonAddItem(String purchaseOrder,SaleOrderDTO saleOrderDto){

        SalesOrder salesOrder = addItem(purchaseOrder, saleOrderDto);
        salesOrder.setStatus(StatusCode.PENDING.getVal());
//        salesOrderService.save(salesOrder);

//        //插入到订单审核表中
//        SalesOrder salesOrderLast = salesOrderService.getOne(new QueryWrapper<SalesOrder>()
//        .orderByDesc("id").last("limit 1"));
//        insetCheck(salesOrderLast,1);
        identityService.setAuthenticatedUserId(ShiroKit.getUserNotNull().getId() + "");
        //启动流程实例，字符串"vacation"是BPMN模型文件里process元素的id
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("pc_sales_order");
        salesOrder.setProcessInstanceId(processInstance.getId());
        salesOrderService.save(salesOrder);
        //流程实例启动后，流程会跳转到经销商提交
        Task vacationApply = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        //设置经销商提交任务的执行人
        taskService.setAssignee(vacationApply.getId(), ShiroKit.getUserNotNull().getId() + "");
        //完成经销商提交任务
        taskService.complete(vacationApply.getId());
    }



    /**
     * 新增销售单公用类
      * @param purchaseOrder
     */
    public SalesOrder addItem(String purchaseOrder,SaleOrderDTO saleOrderDto){

        List<PurchaseOrdersParam> purchaseOrders = JSON.parseArray(purchaseOrder,PurchaseOrdersParam.class);
        StringBuilder builder = new StringBuilder();
        PurchaseOrders purchaseOrderInsert = null;
        //插入采购单
        for (PurchaseOrdersParam purchaseOrdersNew : purchaseOrders){
            purchaseOrderInsert = new PurchaseOrders();
            BeanUtils.copyProperties(purchaseOrdersNew,purchaseOrderInsert);
            purchaseOrdersService.save(purchaseOrderInsert);
            PurchaseOrders purchaseOrdersLast = purchaseOrdersService.getOne(new QueryWrapper<PurchaseOrders>()
                    .lambda()
                    .orderByDesc(PurchaseOrders::getPurchaseId)
                    .last(" limit 1 "));
            builder.append(purchaseOrdersLast.getPurchaseId()+",");
        }

        //插入销售单
        SalesOrder salesOrder = new SalesOrder();
        //1获取最近的一条记录生成订单编号
        SalesOrder salesOrderLast  = salesOrderService.getOne(new QueryWrapper<SalesOrder>()
                .orderByDesc("id").last("limit 1"));
        if (ToolUtil.isNotEmpty(salesOrderLast)){
            salesOrder.setSerialNumOrder(Katrina_CJ_Utils.createOrderSerial(Order.XS_,salesOrderLast.getId()));
        }else {
            salesOrder.setSerialNumOrder(Katrina_CJ_Utils.createOrderSerial(Order.XS_,(long)1));
        }
        //1.获取操作人
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        salesOrder.setSalesUserId(shiroUser.getId());

        //2.获取操作人部门两级部门拼接起来
        StringBuilder stringBuilder= new StringBuilder();
        Long deptId = ShiroKit.getUser().getDeptId();
        Dept dept = deptService.getById(deptId);
        if (ToolUtil.isNotEmpty(dept)){
            stringBuilder.append(dept.getSimpleName());
            Dept deptLast=deptService.getById(dept.getPid());
            if (ToolUtil.isNotEmpty(deptLast)){
                stringBuilder.append(deptLast.getSimpleName());
            }
            salesOrder.setSalesDept(stringBuilder.toString());
        }
        //3.获取购买人员的详细信息
        BeanUtils.copyProperties(saleOrderDto,salesOrder);
        salesOrder.setAddressId(Long.parseLong(saleOrderDto.getAddressId()));
        salesOrder.setPurchaseOrderId(builder.toString().substring(0,builder.length()-1));
        //4.获取当前时间
        salesOrder.setCreateTime(new Date());
        salesOrder.setDealStatus(StatusCode.PENDING.getVal());
        return  salesOrder;
    }

    /**
     * 插入订单审核表中
     * @param salesOrder
     */
    public void insetCheck(SalesOrder salesOrder,Integer code){
        SalsOrderCheck salsOrderCheck = new SalsOrderCheck();
        DealerLevel dealerLevel = dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
        .eq("sys_user_id",ShiroKit.getUserNotNull().getDeptId()));
        if (ToolUtil.isNotEmpty(dealerLevel)){
            salsOrderCheck.setAddressId(dealerLevel.getAreaId());
        }
        salsOrderCheck.setAuditor(ShiroKit.getUserNotNull().getId());
        salsOrderCheck.setIndetOrderId(salesOrder.getId());
        salsOrderCheck.setTime(new Date());
        if (code == 1){
            salsOrderCheck.setStatus(StatusCode.PENDING.getVal());
        }else  if(code == 2){
            salsOrderCheck.setStatus(StatusCode.SALSPENDING.getVal());
        }

        salsOrderCheckService.save(salsOrderCheck);
    }




    /**
     * 申请特价单
     * @param purchaseOrder
     * @param saleOrderDto
     */
    public  void specialAddItem(String purchaseOrder,SaleOrderDTO saleOrderDto){

        //插入需要审核的特价商品
        SalesOrder salesOrder = addItem(purchaseOrder, saleOrderDto);
        salesOrder.setSpecialPriceStaus(StatusCode.PENDING.getVal());
//        salesOrderService.save(salesOrder);
//
//        //同时插入订单审核表
//        SalesOrder salesOrderLast = salesOrderService.getOne(new QueryWrapper<SalesOrder>()
//                .orderByDesc("id").last("limit 1"));
//        insetCheck(salesOrder, 2);
        identityService.setAuthenticatedUserId(ShiroKit.getUserNotNull().getId() + "");
        //启动流程实例，字符串"vacation"是BPMN模型文件里process元素的id
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("pc_special_sales_order");
        salesOrder.setProcessInstanceId(processInstance.getId());
        salesOrderService.save(salesOrder);
        //流程实例启动后，流程会跳转到经销商提交
        Task vacationApply = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        //设置经销商提交任务的执行人
        taskService.setAssignee(vacationApply.getId(), ShiroKit.getUserNotNull().getId() + "");
        //完成经销商提交任务
        taskService.complete(vacationApply.getId());
    }


    /**
     * 普通提交审核
      * @param checkDTO
     * @return
     */
   public void checkCommon(CheckDTO checkDTO){

       SalsOrderCheck salsOrderCheck = salsOrderCheckService.getById(checkDTO.getId());
       switch (salsOrderCheck.getStatus()){

           case 0:
               if (checkDTO.getCode() == SalesOrderCode.PASS.getVal()){
                   //1.经销商审核通过 修改销售订单状态值

                   salsOrderCheck.setStatus(SalesOrderCode.NODE1.getVal());
                   salsOrderCheck.setPass(SalesOrderCode.PASS.getVal());
                   salsOrderCheck.setTime(new Date());
                   salsOrderCheck.setAuditor(ShiroKit.getUserNotNull().getId());
                   salsOrderCheckService.getBaseMapper().updateById(salsOrderCheck);

                   //插入审核记录
                   CheckSales checkSales = new CheckSales();
                   checkSales.setSalesOrderId(salsOrderCheck.getIndetOrderId());
                   checkSales.setTime(new Date());
                   checkSales.setStatus(SalesOrderCode.PASS.getVal());
                   checkSales.setAuditor(ShiroKit.getUserNotNull().getId());
                   checkSales.setAdvice(checkDTO.getAdvice());
                   checkSales.setNode(SalesOrderCode.NODE1.getMessage());
                   checkSalesService.save(checkSales);

                   //2修改销售订单状态值
                   SalesOrder salesOrder = salesOrderService.getById(salsOrderCheck.getIndetOrderId());
                   salesOrder.setStatus(SalesOrderCode.NODE1.getVal());
                   salesOrder.setDealStatus(SalesOrderCode.NODE1.getVal());
                   salesOrderService.getBaseMapper().updateById(salesOrder);
               }else {
                   salsOrderCheck.setAuditor(ShiroKit.getUserNotNull().getId());
                   salsOrderCheck.setTime(new Date());
                   salsOrderCheck.setPass(SalesOrderCode.FAUILT.getVal());
                   salsOrderCheck.setStatus(SalesOrderCode.FAUILT.getVal());
                   salsOrderCheckService.getBaseMapper().updateById(salsOrderCheck);
                   //更新销售单
                   SalesOrder salesOrder = salesOrService.getById(salsOrderCheck.getIndetOrderId());
                   salesOrder.setStatus(SalesOrderCode.FAUILT.getVal());
                   salesOrderService.getBaseMapper().updateById(salesOrder);
               }

           case 1:
               //仓库发货，生成发货单和出库单
               SalesOrder salesOrder = salesOrService.getById(salsOrderCheck.getIndetOrderId());
               DispatchOrder dispatchOrder = new DispatchOrder();
               dispatchOrder.setPurchaseOrdersId(salesOrder.getPurchaseOrderId());
               dispatchOrder.setSalesId(salesOrder.getId());
               dispatchOrder.setCheckCode(StatusCode.SUCCESS.getVal());
               dispatchOrder.setDealerId(salesOrder.getSalesUserId());

               //找出最近的一个发货id
               DispatchOrder dispatchOrderLast = dispatchOrderService.getOne(new QueryWrapper<DispatchOrder>()
               .lambda().orderByDesc(DispatchOrder::getId).last("limit 1"));

               if (ToolUtil.isNotEmpty(dispatchOrderLast)){
                   dispatchOrder.setOrderNum(Katrina_CJ_Utils.createOrderSerial(Order.FH_,dispatchOrderLast.getId()));
               }else {
                   dispatchOrder.setOrderNum(Katrina_CJ_Utils.createOrderSerial(Order.FH_,(long)1));
               }
               dispatchOrderService.getBaseMapper().insert(dispatchOrder);

               //找出最近生成的一个订货单
               DispatchOrder dispatchOrderNew = dispatchOrderService.getOne(new QueryWrapper<DispatchOrder>()
                       .lambda().orderByDesc(DispatchOrder::getId).last("limit 1"));
               //自动生成出库单
               checkDTO.setId(dispatchOrderNew.getId());
               commonService.salsOutOrder(checkDTO);

               //更新状态值
               salesOrder.setDealStatus(StatusCode.DONE.getVal());
               salesOrderService.getBaseMapper().updateById(salesOrder);
       }
   }


    /**
     * 特价审核
     * @param checkDTO
     */
   public  void specialCheck(CheckDTO checkDTO){


       SalsOrderCheck salsOrderCheck = salsOrderCheckService.getById(checkDTO.getId());
       if (checkDTO.getCode() == StatusCode.SUCCESS.getVal()){
           salsOrderCheck.setStatus(SalesOrderCode.SPECIALNODE1.getVal());
           salsOrderCheck.setPass(StatusCode.SUCCESS.getVal());
           salsOrderCheck.setTime(new Date());
           salsOrderCheck.setAuditor(ShiroKit.getUserNotNull().getId());
           salsOrderCheck.setRemark(checkDTO.getAdvice());
           salsOrderCheckService.getBaseMapper().updateById(salsOrderCheck);

           //插入审核记录
           CheckSales checkSales = new CheckSales();
           checkSales.setAdvice(checkDTO.getAdvice());
           checkSales.setAuditor(ShiroKit.getUserNotNull().getId());
           checkSales.setStatus(StatusCode.SUCCESS.getVal());
           checkSales.setTime(new Date());
           checkSales.setSalesOrderId(salsOrderCheck.getIndetOrderId());
           checkSalesService.save(checkSales);

           //更改特价状态的销售订单中的订单状态
           SalesOrder salesOrder = salesOrderService.getById(salsOrderCheck.getIndetOrderId());
           salesOrder.setSpecialPriceStaus(StatusCode.SUCCESS.getVal());
           salesOrderService.getBaseMapper().updateById(salesOrder);
       }else if (checkDTO.getCode() == StatusCode.FAIL.getVal()){

           //修改特价销售单的状态值
           SalesOrder salesOrder = salesOrderService.getById(salsOrderCheck.getIndetOrderId());
           salesOrder.setSpecialPriceStaus(StatusCode.FAIL.getVal());
           salesOrderService.getBaseMapper().updateById(salesOrder);

           //插入审核记录
           CheckSales checkSales = new CheckSales();
           checkSales.setSalesOrderId(salesOrder.getId());
           checkSales.setTime(new Date());
           checkSales.setStatus(StatusCode.FAIL.getVal());
           checkSales.setAuditor(ShiroKit.getUserNotNull().getId());
           checkSales.setNode(SalesOrderCode.SPECIALNODE1.getMessage());
           checkSalesService.save(checkSales);

           //删除当前审核订单的审核
           salsOrderCheckService.getBaseMapper().deleteById(checkDTO.getId());
       }
   }


     /**
     * 普通提交退回
     * @param checkDTO
     */
    public void commonBack(CheckDTO checkDTO){
        //只能退回到经销商/门店节点
        SalsOrderCheck salsOrderCheck = salsOrderCheckService.getById(checkDTO.getId());
        salsOrderCheck.setStatus(SalesOrderCode.BACK.getVal());
        salsOrderCheck.setRemark(checkDTO.getAdvice());
        salsOrderCheck.setAuditor(ShiroKit.getUserNotNull().getId());
        salsOrderCheck.setTime(new Date());
        salsOrderCheck.setPass(SalesOrderCode.FAUILT.getVal());
        salsOrderCheckService.getBaseMapper().updateById(salsOrderCheck);


        //插入审核记录表
        CheckSales checkSales = new CheckSales();
        checkSales.setNode(SalesOrderCode.NODE1.getMessage());
        checkSales.setAuditor(ShiroKit.getUserNotNull().getId());
        checkSales.setTime(new Date());
        checkSales.setSalesOrderId(salsOrderCheck.getIndetOrderId());
        checkSales.setAdvice(checkDTO.getAdvice());
        checkSalesService.save(checkSales);


        //更改特价销售单中的状态值
         SalesOrder salesOrder = salesOrderService.getById(salsOrderCheck.getIndetOrderId());
         salesOrder.setStatus(SalesOrderCode.BACK.getVal());
         salesOrderService.getBaseMapper().updateById(salesOrder);
     }


    /**
     * 特价审核退回
     * @param checkDTO
     */
    public   void specialBack(CheckDTO checkDTO){
         SalsOrderCheck salsOrderCheck = salsOrderCheckService.getById(checkDTO.getId());
         salsOrderCheck.setStatus(SalesOrderCode.BACK.getVal());
         salsOrderCheck.setRemark(checkDTO.getAdvice());
         salsOrderCheck.setAuditor(ShiroKit.getUserNotNull().getId());
         salsOrderCheck.setTime(new Date());
         salsOrderCheck.setPass(SalesOrderCode.FAUILT.getVal());
         salsOrderCheckService.getBaseMapper().updateById(salsOrderCheck);


         //插入审核记录表
         CheckSales checkSales = new CheckSales();
         checkSales.setNode(SalesOrderCode.SPECIALNODE1.getMessage());
         checkSales.setAuditor(ShiroKit.getUserNotNull().getId());
         checkSales.setTime(new Date());
         checkSales.setSalesOrderId(salsOrderCheck.getIndetOrderId());
         checkSales.setAdvice(checkDTO.getAdvice());
         checkSalesService.save(checkSales);

         //更改特价销售单中的状态值
         SalesOrder salesOrder = salesOrderService.getById(salsOrderCheck.getIndetOrderId());
         salesOrder.setSpecialPriceStaus(SalesOrderCode.BACK.getVal());
         salesOrderService.getBaseMapper().updateById(salesOrder);
     }

}
